package com.wangsh.users.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wangsh.common.pojo.ApiResponse;
import com.wangsh.common.pojo.ApiResponseEnum;
import com.wangsh.common.pojo.JSONEnum;
import com.wangsh.common.service.BaseServiceImpl;
import com.wangsh.common.util.ConstatFinalUtil;
import com.wangsh.common.util.PageInfoUtil;
import com.wangsh.users.dao.IAAdminsDao;
import com.wangsh.users.dao.IAStaffDao;
import com.wangsh.users.dao.IAUsersDao;
import com.wangsh.users.pojo.AAdmins;
import com.wangsh.users.pojo.AStaff;
import com.wangsh.users.pojo.AUsers;
import com.wangsh.users.pojo.AUsersEnum;
import com.wangsh.users.service.IUsersDbService;

/**
 * 用户 Db Service Impl
 * @author Tm
 *
 */
@Service("usersDbService")
public class UsersDbServiceImpl extends BaseServiceImpl implements IUsersDbService {
	@Resource
	private IAAdminsDao adminsDao;
	@Resource
	private IAUsersDao usersDao;
	@Resource
	private IAStaffDao staffDao;

	@Override
	public ApiResponse<Object> saveOneAdminsService(AAdmins admins) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		// 添加管理员密码的时候,进行加密.
		admins.setPassword(this.encryptUtil.encodeStr(admins.getPassword()));
		/* 查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("email", admins.getEmail());
		ApiResponse<AAdmins> apiRes = this.findOneAdminsService(condMap);
		/* 获取对象 */
		AAdmins adminRes = apiRes.getDataOneJava();
		if (adminRes != null) {
			/* 用户名已经存在,请换一个 */
			apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
			return apiResponse;
		}

		admins.setCreateTime(new Date());
		admins.setUpdateTime(new Date());
		admins.setLastLoginTime(new Date());

		int res = this.adminsDao.save(admins);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), admins.getId());
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> updateOneAdminsService(AAdmins admins) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("email", admins.getEmail());
		ApiResponse<AAdmins> apiRes = this.findOneAdminsService(condMap);
		/* 获取对象 */
		AAdmins adminRes = apiRes.getDataOneJava();
		if (adminRes != null && adminRes.getId() != admins.getId()) {
			/* 用户名已经存在,请换一个 */
			apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
			return apiResponse;
		}

		admins.setUpdateTime(new Date());
		int res = this.adminsDao.update(admins);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), admins.getId());
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> deleteOneAdminsService(Map<String, Object> condMap) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		int res = this.adminsDao.delete(condMap);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<AAdmins> findOneAdminsService(Map<String, Object> condMap) {
		ApiResponse<AAdmins> apiResponse = new ApiResponse<AAdmins>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		Map<String, AAdmins> data = new HashMap<String, AAdmins>();
		AAdmins admins = this.adminsDao.findOne(condMap);
		data.put(ApiResponseEnum.NAME_ONE.getName(), admins);
		/* 将结果放到JSON中 */
		apiResponse.setDataOne(data);
		apiResponse.setDataOneJava(admins);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<AAdmins> findCondListAdminsService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap) {
		ApiResponse<AAdmins> apiResponse = new ApiResponse<AAdmins>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		List<AAdmins> adminsList = Collections.EMPTY_LIST;

		Map<String, List<AAdmins>> dataList = new HashMap<String, List<AAdmins>>();
		/* 对关键字进行模糊匹配 */
		if (condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + "")) {
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}

		/* 设置分页相关信息 */
		if (pageInfoUtil != null) {
			/* 设置分页信息 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			adminsList = this.adminsDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			/* 向接口中放分页信息 */
			apiResponse.setPageInfoUtil(pageInfoUtil);
		} else {
			adminsList = this.adminsDao.findList(condMap);
		}

		/* 将结果放到JSON中 */
		dataList.put(ApiResponseEnum.NAME_LIST.getName(), adminsList);
		apiResponse.setDataListJava(adminsList);
		apiResponse.setDataList(dataList);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> saveOneUsersService(AUsers users) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		Map<String, AUsers> data = new HashMap<String, AUsers>();
		/* 查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("email", users.getEmail());
		ApiResponse<AUsers> apiRes = this.findOneUsersService(condMap);
		/* 获取对象 */
		AUsers userRes = apiRes.getDataOneJava();
		if (userRes != null) {
			/* 用户名已经存在,请换一个 */
			apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
			return apiResponse;
		}
		
		users.setStatus(AUsersEnum.STATUS_ENABLE.getStatus());
		
		users.setCreateTime(new Date());
		users.setUpdateTime(new Date());
		users.setLastLoginTime(new Date());

		int res = this.usersDao.save(users);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), users.getId());
			data.put(ApiResponseEnum.NAME_ONE.getName(), users);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> updateOneUsersService(AUsers users) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("email", users.getEmail());
		ApiResponse<AUsers> apiRes = this.findOneUsersService(condMap);
		/* 获取对象 */
		AUsers userRes = apiRes.getDataOneJava();
		if (userRes != null && userRes.getId() != users.getId()) {
			/* 用户名已经存在,请换一个 */
			apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
			return apiResponse;
		}
		
		users.setUpdateTime(new Date());

		int res = this.usersDao.update(users);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), users.getId());
			dataMap.put(ApiResponseEnum.NAME_ONE.getName(), users);

			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> updateOneUsersService(AUsers users, Map<String, Object> paramsMap) {
		/* 先更新用户的信息 */
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		try {
			String fileName = paramsMap.get("fileName") + "";
			InputStream is = (InputStream) paramsMap.get("inputStream");

			/* 上传文件的相对路径 /uploadfile/ */
			String uploadFile = ConstatFinalUtil.CONFIG_JSON.getString("website.uploadFile");
			/* 存储的是网址的绝对路径 */
			//String souPath = users.getPhotoPath();
			String souPath = "";
			/*
			 * 真实路径
			 * D:/项目空间/usersCenter/usersCenter-web/usersCenter-web-head/src/main/webapp/
			 */
			String truePath = ConstatFinalUtil.CONFIG_JSON.getString("website.truePath");
			/* 网站的相对路径 */
			String tarRelaPath = uploadFile + "users/" + this.dateFormatUtil.dateStr(new Date()) + "/"
					+ UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
			File tarTrueFile = new File(truePath + tarRelaPath.substring(1));

			/* 创建父目录 */
			if (!tarTrueFile.getParentFile().exists()) {
				tarTrueFile.getParentFile().mkdirs();
			}
			//users.setPhotoPath(tarRelaPath);
			FileOutputStream fos = new FileOutputStream(tarTrueFile);
			/* 复制文件 */
			boolean flag = this.fileUtil.copyFile(is, fos);
			if (flag) {
				if (souPath != null && !"".equalsIgnoreCase(souPath)) {
					souPath = truePath + souPath.substring(1);
					/* 相对路径 */
					File souFile = new File(souPath);
					if (!souFile.delete()) {
						ConstatFinalUtil.SYS_LOGGER.error("删除原始文件失败:原始文件路径:{}", souFile.getAbsolutePath());
					}
				}
			}

			apiResponse = this.updateOneUsersService(users);
		} catch (Exception e) {
			ConstatFinalUtil.SYS_LOGGER.error("上传头像失败了,email:{}", users.getEmail(), e);
		}
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> deleteOneUsersService(Map<String, Object> condMap) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		int res = this.usersDao.delete(condMap);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<AUsers> findOneUsersService(Map<String, Object> condMap) {
		ApiResponse<AUsers> apiResponse = new ApiResponse<AUsers>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		Map<String, AUsers> data = new HashMap<String, AUsers>();
		AUsers users = this.usersDao.findOne(condMap);

		data.put(ApiResponseEnum.NAME_ONE.getName(), users);

		/* 将结果放到JSON中 */
		apiResponse.setDataOne(data);
		apiResponse.setDataOneJava(users);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<AUsers> findCondListUsersService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap) {
		ApiResponse<AUsers> apiResponse = new ApiResponse<AUsers>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		List<AUsers> usersList = Collections.EMPTY_LIST;

		Map<String, List<AUsers>> dataList = new HashMap<String, List<AUsers>>();
		/* 对关键字进行模糊匹配 */
		if (condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + "")) {
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}

		/* 设置分页相关信息 */
		if (pageInfoUtil != null) {
			/* 设置分页信息 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			usersList = this.usersDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			/* 向接口中放分页信息 */
			apiResponse.setPageInfoUtil(pageInfoUtil);
		} else {
			usersList = this.usersDao.findList(condMap);
		}
		/* 将结果放到JSON中 */
		dataList.put(ApiResponseEnum.NAME_LIST.getName(), usersList);
		apiResponse.setDataListJava(usersList);
		apiResponse.setDataList(dataList);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}
	
	@Override
	public ApiResponse<Object> saveOneStaffService(AStaff staff) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		// 添加员工密码的时候,进行加密.
		staff.setPassword(this.encryptUtil.encodeStr(staff.getPassword()));
		/* 查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("email", staff.getEmail());
		ApiResponse<AStaff> apiRes = this.findOneStaffService(condMap);
		/* 获取对象 */
		AStaff adminRes = apiRes.getDataOneJava();
		if (adminRes != null) {
			/* 用户名已经存在,请换一个 */
			apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
			return apiResponse;
		}

		staff.setCreateTime(new Date());
		staff.setUpdateTime(new Date());
		staff.setLastLoginTime(new Date());

		int res = this.staffDao.save(staff);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), staff.getId());
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> updateOneStaffService(AStaff staff) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 查询条件 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("email", staff.getEmail());
		ApiResponse<AStaff> apiRes = this.findOneStaffService(condMap);
		/* 获取对象 */
		AStaff adminRes = apiRes.getDataOneJava();
		if (adminRes != null && adminRes.getId() != staff.getId()) {
			/* 用户名已经存在,请换一个 */
			apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_EXISTS.getStatus());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
			return apiResponse;
		}

		staff.setUpdateTime(new Date());
		int res = this.staffDao.update(staff);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), staff.getId());
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> deleteOneStaffService(Map<String, Object> condMap) {
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		int res = this.staffDao.delete(condMap);
		if (res > 0) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else {
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<AStaff> findOneStaffService(Map<String, Object> condMap) {
		ApiResponse<AStaff> apiResponse = new ApiResponse<AStaff>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		Map<String, AStaff> data = new HashMap<String, AStaff>();
		AStaff staff = this.staffDao.findOne(condMap);
		data.put(ApiResponseEnum.NAME_ONE.getName(), staff);
		/* 将结果放到JSON中 */
		apiResponse.setDataOne(data);
		apiResponse.setDataOneJava(staff);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<AStaff> findCondListStaffService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap) {
		ApiResponse<AStaff> apiResponse = new ApiResponse<AStaff>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		List<AStaff> staffList = Collections.EMPTY_LIST;

		Map<String, List<AStaff>> dataList = new HashMap<String, List<AStaff>>();
		/* 对关键字进行模糊匹配 */
		if (condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + "")) {
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}

		/* 设置分页相关信息 */
		if (pageInfoUtil != null) {
			/* 设置分页信息 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			staffList = this.staffDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			/* 向接口中放分页信息 */
			apiResponse.setPageInfoUtil(pageInfoUtil);
		} else {
			staffList = this.staffDao.findList(condMap);
		}

		/* 将结果放到JSON中 */
		dataList.put(ApiResponseEnum.NAME_LIST.getName(), staffList);
		apiResponse.setDataListJava(staffList);
		apiResponse.setDataList(dataList);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}
}
